/**
 * 1. 配网：使用ESP Touch V2 配网，自定义数据为MQTT server URI
 * 2. 配置设备：设备默认订阅配置主题 <config/mac地址>，Android App 端通过MQTT协议下发配置信息,
 *            将其保存到设备内部NVS存储器中，然后取消订阅。
 * 3. 配置信息：topic前缀
 * 4. 订阅：topic前缀 + mac地址 + command,
 * 5. 发布：topic前缀 + mac地址 + state,
 * 6. 发布信息：mac地址 + state
 */

#include "driver/gpio.h"

#include "esp_log.h"
#include "esp_mac.h"
#include "esp_smartconfig.h"
#include "esp_system.h"
#include "esp_wifi.h"

#include "freertos/event_groups.h"

#include "mqtt_client.h"

#include "nvs_flash.h"

// 使用GPIO13控制继电器，高电平接通，低电平断开
#define RELAY_PIN GPIO_NUM_13
// 当ESP32启动时，检测到GPIO6为低电平时，清除配网信息，进入可重新配网的模式
#define RESET_PIN GPIO_NUM_6

static const char *TAG = "MQTT_TEST";

// 持久化存储信息，命名空间
#define NVS_NAMESPACE "mqtt"
// 存储网络状态
#define NVS_KEY_NETWORK_STATE "network_state"
#define NVS_KEY_MQTT_STATE "mqtt_state"
enum AppState
{
    NETWORK_STATE_UNCONFIGURED,
    NETWORK_STATE_CONFIGURED,
    MQTT_STATE_UNCONFIGURED,
    MQTT_STATE_CONFIGURED,
};
#define NVS_KEY_MQTT_URI "mqtt_uri"
#define NVS_KEY_MQTT_TOPIC "mqtt_topic"
#define NVS_KEY_MQTT_USER "mqtt_user"
#define NVS_KEY_MQTT_PASSWORD "mqtt_password"

static EventGroupHandle_t s_mqtt_event_group;
static const int WIFI_CONFIGURED_BIT = BIT0;
static const int ESPTOUCH_DONE_BIT = BIT1;
static const int MQTT_CONFIGURED_BIT = BIT2;

// MQTT服务器相关信息
#define MQTT_SUB_TOPIC "shop/light/1/command"
#define MQTT_PUB_TOPIC "shop/light/1/attribute"
#define LIGHT_COMMAND_OFF "OFF"
#define LIGHT_COMMAND_ON "ON"
#define LIGHT_COMMAND_REPORT "REPORT"
char *mqtt_uri;
char *mqtt_username;
char *mqtt_password;
char *mqtt_pub_topic;
char mqtt_config_topic[50] = "config/";
char mac_str[13] = {0};

// 初始化nvs
void init_nvs(void)
{
    ESP_LOGD(TAG, "Initialize NVS.");

    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    ESP_LOGD(TAG, "Initialize NVS Done.");
}

void init_gpio(void)
{
    ESP_LOGD(TAG, "Initialize GPIO.");

    // 配置继电器控制端口
    gpio_set_direction(RELAY_PIN, GPIO_MODE_INPUT_OUTPUT);
    // 配置复位按钮
    gpio_set_direction(RESET_PIN, GPIO_MODE_INPUT);

    ESP_LOGD(TAG, "Initialize GPIO Done.");
}

/**
 * 检查是否需要配网，如果复位端口高电平，则从nvs中读取配网标志。
 * 如果有配网信息标志，则将事件组配网标志位设置为已配置。
 *
 */
void check_config(void)
{
    s_mqtt_event_group = xEventGroupCreate();

    // 如果是低电平，则清除配网标志
    int level = gpio_get_level(RESET_PIN);
    if (level == 0)
    {
        return;
    }
    else
    {
        nvs_handle_t nvs_handle;
        esp_err_t ret = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle);
        if (ret != ESP_OK)
        {
            return;
        }
        int8_t flag = NETWORK_STATE_UNCONFIGURED;
        ESP_ERROR_CHECK(nvs_get_i8(nvs_handle, NVS_KEY_NETWORK_STATE, &flag));
        if (flag == NETWORK_STATE_CONFIGURED)
        {
            xEventGroupSetBits(s_mqtt_event_group, WIFI_CONFIGURED_BIT);
        }

        size_t required_size;
        nvs_get_str(nvs_handle, NVS_KEY_MQTT_URI, NULL, &required_size);
        mqtt_uri = malloc(required_size);
        nvs_get_str(nvs_handle, NVS_KEY_MQTT_URI, mqtt_uri, &required_size);

        flag = MQTT_STATE_UNCONFIGURED;
        nvs_get_i8(nvs_handle, NVS_KEY_MQTT_STATE, &flag);
        if (flag == MQTT_STATE_CONFIGURED)
        {
            xEventGroupSetBits(s_mqtt_event_group, MQTT_CONFIGURED_BIT);

            nvs_get_str(nvs_handle, NVS_KEY_MQTT_TOPIC, NULL, &required_size);
            nvs_get_str(nvs_handle, NVS_KEY_MQTT_TOPIC, mqtt_config_topic, &required_size);
            char *attribute = "attribute";
            mqtt_pub_topic = malloc(strlen(mqtt_config_topic) + strlen(attribute) + 1);
            strcpy(mqtt_pub_topic, mqtt_config_topic);
            strcat(mqtt_pub_topic, "/");
            strcat(mqtt_pub_topic, attribute);

            ESP_LOGI(TAG, "MQTT Pub Topic: %s", mqtt_pub_topic);

            nvs_get_str(nvs_handle, NVS_KEY_MQTT_USER, NULL, &required_size);
            mqtt_username = malloc(required_size);
            nvs_get_str(nvs_handle, NVS_KEY_MQTT_USER, mqtt_username, &required_size);

            nvs_get_str(nvs_handle, NVS_KEY_MQTT_PASSWORD, NULL, &required_size);
            mqtt_password = malloc(required_size);
            nvs_get_str(nvs_handle, NVS_KEY_MQTT_PASSWORD, mqtt_password, &required_size);
        }

        nvs_close(nvs_handle);
    }
}

/**
 * MQTT事件回调函数
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    EventBits_t uxBits = xEventGroupGetBits(s_mqtt_event_group);
    int msg_id;
    switch ((esp_mqtt_event_id_t)event_id)
    {
    case MQTT_EVENT_CONNECTED:
    // 如果已经配置过MQTT
        if (uxBits & MQTT_CONFIGURED_BIT)
        {
            char *command = "command";
            char *topic = malloc(strlen(mqtt_config_topic) + strlen(command) + 1);
            strcpy(topic, mqtt_config_topic);
            strcat(topic, "/");
            strcat(topic, mac_str);
            strcat(topic,"/");
            strcat(topic, command);
            msg_id = esp_mqtt_client_subscribe(client, topic, 1);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d, msg_topic=%s", msg_id, topic);
        } else {
            // 配置MQTT
            msg_id = esp_mqtt_client_subscribe(client, mqtt_config_topic, 1);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d, msg_topic=%s", msg_id, mqtt_config_topic);
            esp_restart();
        }

        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);

        if (!(uxBits & MQTT_CONFIGURED_BIT))
        {
            // 接收配置信息，<topic,username,passwod,>
            if (strncmp(mqtt_config_topic, event->topic, strlen(mqtt_config_topic)) == 0)
            {
                ESP_LOGI(TAG, "Receive mqtt config");
                char *split = ",";
                char *topic = strtok(event->data, split);
                char *username = strtok(NULL, split);
                char *password = strtok(NULL, split);
                printf("topic:%s,username:%s,password:%s\r\n", topic, username, password);

                strcpy(mqtt_config_topic, topic);
                strcat(mqtt_config_topic, "/");
                strcat(mqtt_config_topic, mac_str);

                printf("topic:%s\r\n", mqtt_config_topic);

                nvs_handle_t nvs_handle;
                ESP_ERROR_CHECK(nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle));
                ESP_ERROR_CHECK(nvs_set_i8(nvs_handle, NVS_KEY_MQTT_STATE, MQTT_STATE_CONFIGURED));
                ESP_ERROR_CHECK(nvs_set_str(nvs_handle, NVS_KEY_MQTT_TOPIC, topic));
                ESP_ERROR_CHECK(nvs_set_str(nvs_handle, NVS_KEY_MQTT_USER, username));
                ESP_ERROR_CHECK(nvs_set_str(nvs_handle, NVS_KEY_MQTT_PASSWORD, password));
                nvs_commit(nvs_handle);
                nvs_close(nvs_handle);
            }
        }

        if (strncmp(LIGHT_COMMAND_ON, event->data, strlen(LIGHT_COMMAND_ON)) == 0)
        {
            ESP_LOGI(TAG, "SET SWITCH ON");
            ESP_ERROR_CHECK(gpio_set_level(RELAY_PIN, 1));
            return;
        }

        if (strncmp(LIGHT_COMMAND_OFF, event->data, strlen(LIGHT_COMMAND_OFF)) == 0)
        {
            ESP_LOGI(TAG, "SET SWITCH OFF");
            ESP_ERROR_CHECK(gpio_set_level(RELAY_PIN, 0));
            return;
        }

        if (strncmp(LIGHT_COMMAND_REPORT, event->data, strlen(LIGHT_COMMAND_REPORT)) == 0)
        {

            int level = gpio_get_level(RELAY_PIN);
            printf("level:%d\r\n", level);

            if (level == 0)
            {
                esp_mqtt_client_publish(client, mqtt_pub_topic, LIGHT_COMMAND_OFF, strlen(LIGHT_COMMAND_OFF), 0, 0);
            }
            else
            {
                esp_mqtt_client_publish(client, mqtt_pub_topic, LIGHT_COMMAND_ON, strlen(LIGHT_COMMAND_ON), 0, 0);
            }
            return;
        }
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT)
        {
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

/**
 * 连接MQTT服务器
 */
static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = mqtt_uri,
    };
    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    ESP_ERROR_CHECK(esp_mqtt_client_start(client));
}

/**
 * @brief SmartConfig事件的回调函数，用于配置网络，并将配置信息保存到nvs中
 */
static void smartconfig_task(void *parm)
{
    EventBits_t uxBits;
    ESP_ERROR_CHECK(esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_V2));
    smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_smartconfig_start(&cfg));
    while (1)
    {
        uxBits = xEventGroupWaitBits(s_mqtt_event_group, ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY);
        if (uxBits & ESPTOUCH_DONE_BIT)
        {
            esp_smartconfig_stop();
            vTaskDelete(NULL);
        }
    }
}

/**
 * @brief WiFi事件的回调函数
 */
// 配网重试次数
static void event_handler(void *event_handler_arg,
                          esp_event_base_t event_base,
                          int32_t event_id,
                          void *event_data)
{
    // WiFi事件，已经准备好连接
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
    {
        // 如果nvs中有配网信息，则直接开始联网
        EventBits_t uxBits = xEventGroupGetBits(s_mqtt_event_group);
        if (uxBits & WIFI_CONFIGURED_BIT)
        {
            ESP_ERROR_CHECK(esp_wifi_connect());
        }
        // 如果没有配网信息，则开始配网
        else
        {
            xTaskCreate(smartconfig_task, "smartconfig_task", 4096, NULL, 3, NULL);
        }
    }
    // WiFi事件，连接断开
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        // 重新连接WiFi
        ESP_ERROR_CHECK(esp_wifi_connect());
        ESP_LOGI(TAG, "retry to connect to the AP");
    }
    // WiFi事件，获得IP地址，在nvs中保存网络已经配置，启动mqtt连接
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        nvs_handle_t nvs_handle;
        ESP_ERROR_CHECK(nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle));
        ESP_ERROR_CHECK(nvs_set_i8(nvs_handle, NVS_KEY_NETWORK_STATE, NETWORK_STATE_CONFIGURED));
        nvs_commit(nvs_handle);
        nvs_close(nvs_handle);

        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        mqtt_app_start();
    }
    // SmartConfig事件，获得WiFi SSID和密码，保存到nvs中
    else if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD)
    {
        smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data;
        wifi_config_t wifi_config;
        bzero(&wifi_config, sizeof(wifi_config_t));
        memcpy(wifi_config.sta.ssid, evt->ssid, sizeof(wifi_config.sta.ssid));
        memcpy(wifi_config.sta.password, evt->password, sizeof(wifi_config.sta.password));
        wifi_config.sta.bssid_set = evt->bssid_set;
        if (wifi_config.sta.bssid_set == true)
        {
            memcpy(wifi_config.sta.bssid, evt->bssid, sizeof(wifi_config.sta.bssid));
        }

        uint8_t rvd_data[33] = {0};
        if (evt->type == SC_TYPE_ESPTOUCH_V2)
        {
            ESP_ERROR_CHECK(esp_smartconfig_get_rvd_data(rvd_data, sizeof(rvd_data)));
            nvs_handle_t nvs_handle;
            ESP_ERROR_CHECK(nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle));
            ESP_ERROR_CHECK(nvs_set_str(nvs_handle, NVS_KEY_MQTT_URI, (char *)rvd_data));
            nvs_commit(nvs_handle);

            // size_t required_size;
            // nvs_get_str(nvs_handle, NVS_KEY_MQTT_URI, NULL, &required_size);
            // char* uri = malloc(required_size);
            // nvs_get_str(nvs_handle, NVS_KEY_MQTT_URI, uri, &required_size);
            nvs_close(nvs_handle);

            // printf("%s\n", uri);
        }

        xEventGroupSetBits(s_mqtt_event_group, WIFI_CONFIGURED_BIT);

        ESP_ERROR_CHECK(esp_wifi_disconnect());
        ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
        esp_wifi_connect();
    }
    else if (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE)
    {
        xEventGroupSetBits(s_mqtt_event_group, ESPTOUCH_DONE_BIT);
    }
}

void init_wifi(void)
{
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config));

    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT,
                                               ESP_EVENT_ANY_ID,
                                               &event_handler,
                                               NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT,
                                               ESP_EVENT_ANY_ID,
                                               &event_handler,
                                               NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(SC_EVENT,
                                               ESP_EVENT_ANY_ID,
                                               &event_handler,
                                               NULL));

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    EventBits_t uxBits = xEventGroupGetBits(s_mqtt_event_group);
    // 如有配网信息，则读取配置
    if (uxBits & WIFI_CONFIGURED_BIT)
    {
        wifi_config_t wifi_config;
        ESP_ERROR_CHECK(esp_wifi_get_config(WIFI_IF_STA, &wifi_config));
    }
    ESP_ERROR_CHECK(esp_wifi_start());
}

void init(void)
{
    uint8_t *mac = (uint8_t *)malloc(6);
    esp_read_mac(mac, ESP_MAC_WIFI_STA);

    for (int i = 0; i < 6; i++)
    {
        uint8_t c1 = mac[i] >> 4;
        if (c1 > 9)
        {
            c1 += 'A' - 10;
        }
        else
        {
            c1 += '0';
        }
        mac_str[i * 2] = c1;

        uint8_t c2 = mac[i] & 0x0F;
        if (c2 > 9)
        {
            c2 += 'A' - 10;
        }
        else
        {
            c2 += '0';
        }
        mac_str[i * 2 + 1] = c2;
    }
    strcat(mqtt_config_topic, mac_str);
    printf("%s\n", mqtt_config_topic);
}

void app_main(void)
{
    ESP_LOGI(TAG, "Starting ......");
    init();
    init_nvs();
    init_gpio();
    check_config();
    init_wifi();
}